#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
配置管理模块
负责配置文件的读写与解析 (JSON格式)
"""

import json
import os
from pathlib import Path


class ConfigManager:
    """配置管理器类"""

    def __init__(self):
        """初始化配置管理器"""
        # 获取配置文件路径 (Windows用户配置目录)
        self.app_name = "WatchdogSoftware"
        self.config_dir = Path(os.path.expandvars(r'%APPDATA%')) / self.app_name
        self.config_file = self.config_dir / "config.json"
        self.log_dir = self.config_dir / "logs"
        
        # 确保配置目录存在
        self.config_dir.mkdir(parents=True, exist_ok=True)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        
        # 默认配置
        self.default_config = {
            "processes": [],
            "autostart": False
        }
        
        # 加载配置
        self.config = self.load_config()

    def load_config(self):
        """
        加载配置文件
        
        Returns:
            dict: 配置信息
        """
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except (json.JSONDecodeError, IOError) as e:
                print(f"加载配置文件出错: {e}")
                return self.default_config.copy()
        else:
            # 配置文件不存在，创建默认配置
            self.save_config(self.default_config)
            return self.default_config.copy()

    def save_config(self, config=None):
        """
        保存配置到文件
        
        Args:
            config (dict): 要保存的配置，如果为None则保存当前配置
        """
        config_to_save = config if config is not None else self.config
        
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config_to_save, f, ensure_ascii=False, indent=4)
        except IOError as e:
            print(f"保存配置文件出错: {e}")

    def get_processes(self):
        """
        获取进程列表
        
        Returns:
            list: 进程配置列表
        """
        return self.config.get("processes", [])

    def add_process(self, process_info):
        """
        添加进程配置
        
        Args:
            process_info (dict): 进程配置信息
        """
        if "processes" not in self.config:
            self.config["processes"] = []
        
        self.config["processes"].append(process_info)
        self.save_config()

    def update_process(self, index, process_info):
        """
        更新进程配置
        
        Args:
            index (int): 进程索引
            process_info (dict): 新的进程配置信息
        """
        if "processes" in self.config and 0 <= index < len(self.config["processes"]):
            self.config["processes"][index] = process_info
            self.save_config()

    def remove_process(self, index):
        """
        删除进程配置
        
        Args:
            index (int): 进程索引
        """
        if "processes" in self.config and 0 <= index < len(self.config["processes"]):
            del self.config["processes"][index]
            self.save_config()

    def get_autostart(self):
        """
        获取开机自启动设置
        
        Returns:
            bool: 是否开机自启动
        """
        return self.config.get("autostart", False)

    def set_autostart(self, enabled):
        """
        设置开机自启动
        
        Args:
            enabled (bool): 是否启用开机自启动
        """
        self.config["autostart"] = enabled
        self.save_config()